package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.TestSoulApi;
import com.tanhua.dubbo.server.pojo.UserSoul;
import com.tanhua.server.enums.CoverEnum;
import com.tanhua.server.enums.LevelEnum;
import com.tanhua.server.enums.NameEnum;
import com.tanhua.server.mapper.SoulQuestionMapper;
import com.tanhua.server.mapper.TemperamentMapper;
import com.tanhua.server.pojo.SoulQuestion;
import com.tanhua.server.pojo.Temperament;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.RandomUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TestSoulService {
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private TemperamentMapper temperamentMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private TestSoulApi testSoulApi;

    private static List<Questions> questionsList=new ArrayList<>();

    public List<Answers> getSoulQuestions() {
        Long userId = UserThreadLocal.get().getId();
        List<Answers> list = new ArrayList<>();
        UserSoul userSoul = this.testSoulApi.findById(userId);
        if (null==userSoul){
            userSoul=new UserSoul();

            userSoul.setUserId(userId);
            userSoul.setQuestionTableOne(0);
            userSoul.setQuestionTableTwo(1);
            userSoul.setQuestionTableThree(1);
            userSoul.setQuestionTableAll(1);
            String s = this.testSoulApi.saveTestResult(userSoul);
            userSoul.setId(new ObjectId(s));
        }



        for (int i = 1; i <= 3; i++) {
            QueryWrapper<SoulQuestion> query=new QueryWrapper<>();
            query.eq("type",i);

            Answers answers = new Answers();


            List<SoulQuestion> soulQuestions = this.soulQuestionMapper.selectList(query);
            List<Questions> questions = new ArrayList<>();


            answers.setId(i+"");
            answers.setName(i==1? NameEnum.simpleName.getName():i==2? NameEnum.secondaryName.getName(): NameEnum.topName.getName());
            answers.setCover(i==1? CoverEnum.simpleCover.getCover():i==2? CoverEnum.secondaryCover.getCover(): CoverEnum.topCover.getCover());
            answers.setLevel(i==1? LevelEnum.simpleLevel.getLevel():i==2? LevelEnum.secondaryLevel.getLevel(): LevelEnum.topLevel.getLevel());
            answers.setStar(i+1);
            answers.setIsLock(i==1?userSoul.getQuestionTableOne():i==2?userSoul.getQuestionTableTwo():userSoul.getQuestionTableThree());
            if (i==1){
                answers.setReportId(userSoul.getQuestionTableTwo()==1?null:userSoul.getId().toHexString());
            }else if (i==2){
                answers.setReportId(userSoul.getQuestionTableThree()==1?null:userSoul.getId().toHexString());
            }else if (i==3){
                answers.setReportId(userSoul.getQuestionTableAll()==1?null:userSoul.getId().toHexString());
            }
            for (SoulQuestion soulQuestion : soulQuestions) {
                List<Options> options = new ArrayList<>();
                Questions question = new Questions();
                question.setId(soulQuestion.getQuestionId().toString());
                question.setQuestion(soulQuestion.getQuestionContext());

                List<String> listselect = new ArrayList<>();
                listselect.add(soulQuestion.getSelectA());
                listselect.add(soulQuestion.getSelectB());
                listselect.add(soulQuestion.getSelectC());
                listselect.add(soulQuestion.getSelectD());
                listselect.add(soulQuestion.getSelectE());
                listselect.add(soulQuestion.getSelectF());
                listselect.add(soulQuestion.getSelectG());
                List<Integer> listscore = new ArrayList<>();
                listscore.add(soulQuestion.getScoreA());
                listscore.add(soulQuestion.getScoreB());
                listscore.add(soulQuestion.getScoreC());
                listscore.add(soulQuestion.getScoreD());
                listscore.add(soulQuestion.getScoreE());
                listscore.add(soulQuestion.getScoreF());
                listscore.add(soulQuestion.getScoreG());
                for (int i1 = 0; i1 < listselect.size(); i1++) {

                    if (listselect.get(i1)!=null) {
                        Options option = new Options();
                        char s=(char)(65+i1);
                        option.setId(s+"");
                        option.setOption(listselect.get(i1));
                        option.setSocre(listscore.get(i1));
                        options.add(option);
                    }else {
                        break;
                    }
                }
                question.setOptions(options);
                questions.add(question);

            }
            answers.setQuestions(questions);
            list.add(answers);
        }

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getIsLock()==1){
                questionsList=list.get(i-1).getQuestions();
                break;
            }
        }


        return list;
    }






/*




    private void setList(){
        List<Map<String, String>> param =new ArrayList<>();
        Map<String,String> map=new HashMap<>();
        map.put("1","A");
        map.put("2","B");
        map.put("3","C");
        map.put("4","D");
        map.put("5","E");
        param.add(map);

        List<Questions> questionsList = new ArrayList<>();
        List<Options> optionsList=new ArrayList<>();
        Options options1=new Options("A","aaa",5);
        Options options2=new Options("B","aaa",4);
        Options options3=new Options("C","aaa",3);
        Options options4=new Options("D","aaa",2);
        Options options5=new Options("E","aaa",1);
        optionsList.add(options1);
        optionsList.add(options2);
        optionsList.add(options3);
        optionsList.add(options4);
        optionsList.add(options5);

        Questions questions=new Questions("1","aaaa",optionsList);
        Questions questions1=new Questions("2","aaaa",optionsList);
        questions.setOptions(optionsList);
        questions1.setOptions(optionsList);

        questionsList.add(questions1);
        questionsList.add(questions);


        QuestionThreadLocal.set(questionsList);
    }
*/

    public String doTestSoul(List<Map<String, String>> param) {
//        setList();
        try {

            int count=0;

            /*        for (Questions question : questions) {
            for (Map<String, String> stringStringMap : param) {
                Set<String> ids = stringStringMap.keySet();
                for (String id : ids) {
                   if (id.equals(question.getId())){
                       List<Options> options = question.getOptions();
                       for (Options option : options) {
                         if (option.getOption().equals(stringStringMap.get(id))){
                             count+=option.getSocre();
                         }
                       }
                   }
                }

            }
        }*/

            /*for (Map<String, String> map : param) {
                for (Questions question : questionsList) {
                    if (map.get("questionId").equals(question.getId())){
                        List<Options> options = question.getOptions();
                        for (Options option : options) {//遍历
                            if (map.get("optionId").equals(option.getId())){
                                count+=option.getSocre();
                                break;
                            }
                        }
                        break;
                    }

                }
            }*/

            for (Map<String, String> stringStringMap : param) {//对用户的答题集合进行遍历
                String optionId = stringStringMap.get("optionId");
                for (Questions questions : questionsList) {//对试卷进行遍历
                    if (optionId.equals(questions.getId())){//找到题号相等的
                        for (Options option : questions.getOptions()) {//给出题号对应的选项
                            if (option.getId().equals(optionId)){//找到与用户对应的选项
                                count+=option.getSocre();//计算分数
                                break;
                            }
                        }
                    }
                }
            }








            QueryWrapper<Temperament> query=new QueryWrapper<>();
            query.ge("max_score",count).le("min_score",count);

            Temperament temperament = this.temperamentMapper.selectOne(query);

//            if (null==temperament){
//                return null;
//            }

            UserSoul userSoul=new UserSoul();

            userSoul.setUserId(UserThreadLocal.get().getId());
//            userSoul.setUserId();
            userSoul.setTypeId(temperament.getId());
            userSoul.setWaiXiang(getRandom());
            userSoul.setPanDuan(getRandom());
            userSoul.setLiXing(getRandom());
            userSoul.setChouXiang(getRandom());
//            TestSoulApi testSoulApi=new TestSoulApiImpl();
            String b = testSoulApi.saveTestResult(userSoul);
            if (null!=b){
                return b;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 生成灵魂报告表
     *
     * @param id
     * @return
     */
    public SoulVo querySoul(String id) {
        User user = UserThreadLocal.get();

        UserSoul userSoul = testSoulApi.queryUserSoulById(id); //报告Id

        //获取temperament中的性格id,插叙他的灵魂结果表
       /* QueryWrapper<Temperament> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", userSoul.getTypeId());
        Temperament temperament = this.temperamentMapper.selectOne(queryWrapper1);*/

        Temperament temperament = this.temperamentMapper.selectById(userSoul.getTypeId());

        //将灵魂结果表赋予对象中并返回
        SoulVo soulVo = new SoulVo();
        soulVo.setCover(temperament.getImg());
        soulVo.setConclusion(temperament.getContext());

        List<Dimensions> dimensions=new ArrayList<>();
        dimensions.add(new Dimensions("外向",userSoul.getWaiXiang()));
        dimensions.add(new Dimensions("判断",userSoul.getPanDuan()));
        dimensions.add(new Dimensions("抽象",userSoul.getChouXiang()));
        dimensions.add(new Dimensions("理性",userSoul.getLiXing()));

/*
        //创键map集合
        Map<String, String> dimensionsMap = new HashMap<>();
        dimensionsMap.put("外向", userSoul.getWaiXiang());  //外向
        dimensionsMap.put("判断", userSoul.getPanDuan());       //判断
        dimensionsMap.put("抽象", userSoul.getChouXiang());  //抽象
        dimensionsMap.put("理性", userSoul.getLiXing());           //理性
*/

        soulVo.setDimensions(dimensions);


        //根据typeId查询所有相同性格的人
        List<UserSoul> userSoulList = this.testSoulApi.queryUserSoulList(userSoul.getTypeId());

        //创建集合用来存放userIds
        List<Long> userIds = new ArrayList<>();

        while (true){
            if (userSoulList.size()>10){
                int i = RandomUtils.nextInt(0, userSoulList.size() - 1);
                UserSoul soul = userSoulList.get(i);
                if (userIds.contains(soul.getUserId())){
                    continue;
                }
                userIds.add(soul.getUserId());
                if (userIds.size()>=10){
                    break;
                }
            }else {
                for (UserSoul soul : userSoulList) {
                    userIds.add(soul.getUserId());
                }
                break;
            }

        }



        //通过userIds来查询用户信息表
        QueryWrapper<UserInfo> queryWrapper2 = new QueryWrapper<>();

        queryWrapper2.in("user_id", userIds);

        List<UserInfo> userInfos = userInfoService.queryUserInfoList(queryWrapper2);


        List<SimilarYou> similarYouMap = new ArrayList<>();

        for (UserInfo userInfo : userInfos) {
            SimilarYou similarYou=new SimilarYou();
            if (user.getId() == userInfo.getUserId()) {
                continue;
            }

            similarYou.setId(Integer.valueOf(userInfo.getUserId().toString()) );
            similarYou.setAvatar(userInfo.getLogo());
            similarYouMap.add(similarYou);
        }

        soulVo.setSimilarYou(similarYouMap);

        return soulVo;


    }

    private String getRandom(){
        int i = RandomUtils.nextInt(6, 9) * 10;
        return i+"%";
    }

}
